package com.gdou.teaching.service.impl;

import com.gdou.teaching.Enum.ClazzStatusEnum;
import com.gdou.teaching.Enum.ResultEnum;
import com.gdou.teaching.Enum.UserIdentEnum;
import com.gdou.teaching.Enum.UserStatusEnum;
import com.gdou.teaching.dataobject.Clazz;
import com.gdou.teaching.dataobject.User;
import com.gdou.teaching.dataobject.UserInfo;
import com.gdou.teaching.dto.UserDTO;
import com.gdou.teaching.exception.TeachingException;
import com.gdou.teaching.mapper.ClazzMapper;
import com.gdou.teaching.mapper.UserInfoMapper;
import com.gdou.teaching.mapper.UserMapper;
import com.gdou.teaching.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.text.Collator;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author carrymaniac
 * @date Created in 19:32 2019-07-27
 * @description User实现类
 **/
@Service
@Slf4j
public class UserServiceImpl  implements UserService{

    @Autowired
    UserMapper userMapper;
    @Autowired
    UserInfoMapper userInfoMapper;
    @Autowired
    ClazzMapper clazzMapper;

    @Override
    public User getUser(int id) {
        return  userMapper.selectUserById(id);
    }

    @Override
    public Boolean register(User user) {
        String userNumber = user.getUserNumber();
        if(userMapper.selectUserByUserNumber(userNumber,null)!=null){
            throw new TeachingException(ResultEnum.USER_INFO_USED);
        }
        String salt = UUID.randomUUID().toString().substring(0,5);
        user.setSalt(salt);
        user.setHeadUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
        user.setPassword(DigestUtils.md5DigestAsHex((user.getPassword()+salt).getBytes()));
        user.setUserStatus(UserStatusEnum.NORMAL.getCode());
        userMapper.addUser(user);
        return true;
    }



    @Override
    public User login(String username, String password) {
        Map<String,Object> map = new HashMap<>();
        if(StringUtils.isEmpty(username)){
            throw new TeachingException(ResultEnum.USER_ID_ERROR);
        }
        if(StringUtils.isEmpty(password)){
            throw new TeachingException(ResultEnum.USER_PASSWORD_EMPTY);
        }
        User user = userMapper.selectUserByUserNumber(username,0);
        if(user==null){
           throw new TeachingException(ResultEnum.USER_INFO_ERROR);
        }
        if(!DigestUtils.md5DigestAsHex((password+user.getSalt()).getBytes()).equals(user.getPassword())){
            throw new TeachingException(ResultEnum.USER_INFO_ERROR);
        }else {
            return user;
        }
    }

    @Override
    public User getUserByUserNumber(String userNumber) {
        return userMapper.selectUserByUserNumber(userNumber,0);
    }

    @Override
    public Boolean addUserByBatch(List<User> users) {
        List<String> userNumbers = users.stream().map(User::getUserNumber).collect(Collectors.toList());
        List<User> userExist = userMapper.selectUserListByUserNumber(userNumbers,null);
        if(userExist.size()>0) {
            log.error("重复的用户信息为:  {}", userExist);
            throw new TeachingException(ResultEnum.USER_INFO_USED);
        }
        return userMapper.addUsers(users)>0;
    }

    @Override
    public Boolean deleteUserByBatch(List<String> userNumbers) {
        if(!userMapper.deleteUsersByUserNumber(userNumbers)){
            throw  new TeachingException(ResultEnum.PARAM_ERROR);
        }
        return true;
    }

    @Override
    public UserDTO getUserByUserId(Integer userId) {
        User user = userMapper.selectUserById(userId);
        if(user==null){
            throw new TeachingException(ResultEnum.USER_NOT_EXIST);
        }
        Clazz clazz = clazzMapper.selectClazzByClassId(user.getClassId(), ClazzStatusEnum.NORMAL.getCode());
        UserInfo userInfo = userInfoMapper.selectUserInfoByUserId(userId);
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user,userDTO);
        BeanUtils.copyProperties(userInfo,userDTO);
        userDTO.setClassName(clazz.getClassName());
        return userDTO;
    }

    @Override
    public List<Map.Entry<Integer, String>> selectTeacherList() {
        List<User> users = userMapper.selectUserListByUserIdent(UserIdentEnum.TEACHER.getCode(), UserStatusEnum.NORMAL.getCode());
        Map<Integer,String> map = new TreeMap<>();
        users.forEach(user -> {
            map.put(user.getUserId(),user.getNickname());
        });
        List<Map.Entry<Integer, String>> list = new ArrayList<>(map.entrySet());
        Collections.sort(list, (o1, o2) -> Collator.getInstance(Locale.CHINESE).compare(o1.getValue(),o2.getValue()));
        return list;
    }

    @Override
    public List<UserDTO> getUsersByUserId(List<Integer> userIds) {
        List<User> userListByIds = userMapper.getUserListByIds(userIds);
        List<UserDTO> collect = userListByIds.stream().map(user -> {
            UserDTO userDTO = new UserDTO();
            BeanUtils.copyProperties(user, userDTO);
            return userDTO;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public Boolean updatePassword(Integer userId, String newPassword) {
        User user = userMapper.selectUserById(userId);
        user.setPassword(DigestUtils.md5DigestAsHex((newPassword+user.getSalt()).getBytes()));
        userMapper.updateUser(user);
        return true;
    }


}
